package cn.itcast.demo.lock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
public class SimpleRedisLock implements RedisLock {

    private String key;

    private StringRedisTemplate redisTemplate;

    public SimpleRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    private static final String VALUE_PREFIX = UUID.randomUUID().toString();

    @Override
    public boolean tryLock(long releaseTime) {
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        return boo != null && boo;
    }

    @Override
    public void unlock() {
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        String cacheValue = redisTemplate.opsForValue().get(key);
        if(value.equals(cacheValue)){
            redisTemplate.delete(key);
        }
    }
}
